package com.ym.utils;

import java.util.*;
import java.util.Map.Entry;

/**
 * Description
 * Created by 王伟
 * Date create on 14:26 2019/11/19.
 */
public class MapHandler {

	/**
	 * 将Map不为null的Object值转化为String
	 */
	public static Map<String, String> obj2StrNotNull(Map<String, ?> map){
		if(null == map || map.isEmpty()){
			return null;
		}
		Map<String, String> res = new HashMap<>();
		for(Entry<String, ?> entry : map.entrySet()){
			if(null == entry.getValue()){
				continue;
			}
			//复杂数据类型，转为json字符串
			if(entry.getValue() instanceof Date){
				res.put(entry.getKey(), DateHandler.getDateString((Date)entry.getValue()));
			}else if(!isSimpleObj(entry.getValue().getClass())){
				res.put(entry.getKey(), JsonUtil.toJson(entry.getValue()));
			}else{
				res.put(entry.getKey(), String.valueOf(entry.getValue()));
			}
		}
		return res;
	}

	/**
	 * map转为list 加key加value
	 */
	public static List<Object> map2List(Map<String, ?> map){
		if(Common.isEmpty(map)){
			return null;
		}
		List<Object> list = new ArrayList<>();
		for(Entry<String, ?> entry : map.entrySet()){
			list.add(entry.getKey());
			list.add(entry.getValue());
		}
		return list;
	}
	
	/**
	 * map转为list 加key
	 */
	public static List<Object> mapKey2List(Map<String, ?> map){
		if(Common.isEmpty(map)){
			return null;
		}
		List<Object> list = new ArrayList<>();
		for(Entry<String, ?> entry : map.entrySet()){
			list.add(entry.getKey());
		}
		return list;
	}
	
	/**
	 * 从map中获得long
	 */
	public static long getLong4Map(Map<String, ?> map,String key){
		return Long.parseLong(String.valueOf(map.get(key)));
	}
	
	/**
	 * 移除map中的空值  空值判断 null ""
	 */
	public static void removeEmptyValue(Map<String, ?> map){
		if(null == map || map.isEmpty()){
			return;
		}
		for(Entry<String, ?> entry : map.entrySet()){
			if(Common.isEmpty(entry.getValue())){
				map.remove(entry.getKey());
			}
		}
	}

	/**
	 * 初始化Map
	 */
	public static Map<String,String> initMap(String...args){
		Map<String,String> map=new HashMap<>();
		if(args.length==0){
			return map;
		}
		int size=args.length%2==0?args.length:args.length-1;
		for (int i = 0; i < size;) {
			map.put(args[i++], args[i++]);
		}
		return map;
	}
	
	public static Map<String,Object> getMap(Object... params){
		if(null == params || params.length == 0){
			return null;
		}
		Map<String,Object> map = new HashMap<String, Object>();
		int size = (params.length%2==0?params.length:params.length-1);
		for (int i = 0; i < size;i = i+2) {
			map.put(String.valueOf(params[i]), params[i+1]);
		}
		return map;
	}
	
	/** 
     * 把数组所有元素排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @param params 需要排除的key字段
     * @return 拼接后字符串
     */
    public static String map2String(Map<String, String> params, String exclude) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        StringBuffer prestr = new StringBuffer();
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            if(exclude.equals(key) || null == params.get(key)){
            	continue;
            }
        	prestr.append("&" + key + "=" + params.get(key));
        }
        return prestr.substring(1);
    }
    
    /**
     * 将map中value为空的去掉
     * @return 
     */
    public static Map<String, String> removeNull(Map<String, String> map){
    	if(Common.isEmpty(map)){
    		return map;
    	}
    	Iterator<Entry<String, String>> it = map.entrySet().iterator();  
        while(it.hasNext()){
            if(null == it.next().getValue()){
            	it.remove(); 
            }
        }
        return map;
    }
    
    /**
	 * 生成签名(没有MD5加密和转换大写)
	 * 把map所有元素字典排序，并按照“参数=参数值”的模式用“&”字符拼接成字符串
	 * @param params
	 * @param key 不需要拼接key的传 空字符串""
	 * @return
	 */
	public static String sign(Map<String, ? extends Object> params, String key) {
		StringBuilder sb = new StringBuilder();
		ArrayList<String> keys = new ArrayList<>(params.size());
		keys.addAll(params.keySet());
		//参数名ASCII码从小到大排序（字典序）；
		Collections.sort(keys);
		for (int i = 0; i < keys.size(); i++) {
			Object val = params.get(keys.get(i));
			//如果参数的值为空不参与加密；签名参数不参与加密;签名类型不参与加密
			if (!"sign_type".equals(keys.get(i)) && !"sign".equals(keys.get(i)) && val != null && String.valueOf(params).trim().length() > 0) {
				sb.append('&').append(keys.get(i)).append('=').append(val);
			}
		}
		if (sb.length() > 0) {
			sb.deleteCharAt(0);
			if(Common.isNotEmpty(key)){
				sb.append("&key=").append(key);
			}
		}
		return sb.toString();
	}
    
	/**是否简单的数据类型：基本数据类型(byte short int long float double char boolean)、Boolean、Character、数字、字符序列、枚举
	 * @param clazz 类型
	 * @return
	 */
	public static boolean isSimpleObj(Class<?> clazz){
		return CharSequence.class.isAssignableFrom(clazz)
				||Number.class.isAssignableFrom(clazz)
				||Boolean.class==clazz||Character.class==clazz
				||clazz.isPrimitive()
				||clazz.isEnum();
	}

	public static Map<String, String> obj2map1(Object obj){
		if(obj==null){
			return null;
		}
		String json = JsonUtil.toJson(obj);
		return MapHandler.obj2StrNotNull(JsonUtil.jsonToBean(json,Map.class));
	}
	public static Map<String, String> obj2map(Object obj){
		if(obj==null){
			return null;
		}
		String json = JsonUtil.toJson(obj);
		return MapHandler.obj2StrNotNull(JsonUtil.jsonToBean(json,Map.class));
	}
}
